package com.example.springboottemplate.Utiles.Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
* 密码加密工具
* 密码作为哈希存在数据库不做明文
*/
@Component
public class Password {

    Logger logger = Logger.getLogger(String.valueOf(Password.class));

    // 哈希密码方法
    public String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(password.getBytes());
            // 将 byte 数组转换为十六进制字符串
            StringBuilder hexHash = new StringBuilder();
            for (byte b : hash) {
                hexHash.append(String.format("%02x", b));
            }
            return hexHash.toString();
        } catch (NoSuchAlgorithmException e) {
            logger.log(Level.parse("hashError"),e.getMessage());
            return null;
        }
    }

    // 验证密码方法
    public boolean authenticate(String inputPassword, String hashedPassword) {
        // 将用户输入的密码进行哈希处理，然后与数据库中存储的哈希值进行比较
        String hashedInputPassword = hashPassword(inputPassword);
        return hashedInputPassword.equals(hashedPassword);
    }
}
